//
//  PicturePicker.m
//  HKIM
//
//  Created by 甬力科技 on 2018/12/19.
//  Copyright © 2018年 xiaohe. All rights reserved.
//

#import "PicturePicker.h"
//#import <Masonry.h>
#import <TZImageManager.h>

#define PictureSize (SCREENWIDTH-80-40)/5
#define interval 10

@interface PicturePicker()<TZImagePickerControllerDelegate>


@property (nonatomic, strong)UIImageView *addImg;

@end

@implementation PicturePicker

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        _pictureArray = [[NSMutableArray alloc] init];
        [self loadui];
    }
    return self;
}

- (void)loadui
{
    self.addImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pictureAdd"]];
    _addImg.backgroundColor = RGBACOLOR(248, 248, 248, 1);
    _addImg.userInteractionEnabled = YES;
    [self addSubview:_addImg];
    _addImg.frame = CGRectMake(0, 0, PictureSize, PictureSize);
    
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image_btn"]];
    [_addImg addSubview:icon];
    icon.center = _addImg.center;
    icon.bounds = CGRectMake(0, 0, 23, 21);
    
    UITapGestureRecognizer *addTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addTapAction:)];
    [_addImg addGestureRecognizer:addTap];
}

- (void)addTapAction:(UITapGestureRecognizer *)tap
{
    TZImagePickerController *imagePickerC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerC.allowCrop = YES;
    imagePickerC.cropRect = CGRectMake(0, (SCREENHEIGHT-SCREENWIDTH)/2, SCREENWIDTH, SCREENWIDTH);
    [[self getCurrentVC] presentViewController:imagePickerC animated:YES completion:nil];
}

- (void)reloadData
{
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    if (_pictureArray.count == 0)
    {
        [self addSubview:_addImg];
        _addImg.frame = CGRectMake(0, 0, PictureSize, PictureSize);
        if (self.index == 1)
        {
            _addImg.userInteractionEnabled = NO;
        }
        if (self.backHeight)
        {
            self.backHeight(PictureSize, self, self.pictureArray);
        }
        return;
    }
    
    UIImageView *lastView = nil;
    for (NSInteger i = 0; i < _pictureArray.count; i++) {
        if (i < 9) {
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.backgroundColor = [UIColor lightGrayColor];
            imageView.clipsToBounds = YES;
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.image = _pictureArray[i];
            imageView.tag = 1000+i;
            [self addSubview:imageView];
            
            UITapGestureRecognizer *tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lookPicture:)];
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:tapAction];
            
            imageView.frame = CGRectMake((PictureSize+interval)*(i%5), (PictureSize+interval)*(i/5), PictureSize, PictureSize);
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [button setImage:[UIImage imageNamed:@"shopDelete"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(deletePicture:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
            button.frame = CGRectMake(imageView.right-14, imageView.top-12, 25, 25);
            
            if (self.index == 1)
            {
                button.hidden = YES;
            }
            else {
                button.hidden = NO;
            }

            
            if (i == (_pictureArray.count - 1))
            {
                lastView = imageView;
            }
        }
    }
    
    if (lastView)
    {
        [self addSubview:_addImg];
        
        if (self.index == 1)
        {//不能编辑 已经上架
            _addImg.hidden = YES;
        }else {//允许编辑
            _addImg.hidden = NO;
        }
        
        if (_pictureArray.count == 5)
        {
            _addImg.frame = CGRectMake(0, lastView.bottom+interval, PictureSize, PictureSize);

        }
        else if (_pictureArray.count == 6)
        {
            _addImg.hidden = YES;
        }
        else {
           _addImg.frame = CGRectMake(lastView.right+interval, lastView.top, PictureSize, PictureSize);
        }
        UITapGestureRecognizer *addTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addTapAction:)];
        [_addImg addGestureRecognizer:addTap];
    }
    
    float selfHeight = 0;
    if (_pictureArray.count <= 4) {

        selfHeight = PictureSize;
    }
    else if (_pictureArray.count <= 9) {

        selfHeight = PictureSize + interval + PictureSize;
    }

    
    if (self.backHeight)
    {
        self.backHeight(selfHeight, self, self.pictureArray);
    }
}

- (void)lookPicture:(UITapGestureRecognizer *)tap
{
    NSInteger tag = tap.view.tag - 1000;
    NSLog(@"%ld", tag);
}

- (void)deletePicture:(UIButton *)button
{
    [_pictureArray removeObjectAtIndex:button.indexPath.row];
    [self reloadData];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    
//    for (NSInteger i = 0; i < photos.count; i++) {
//        if (_pictureArray.count < 6) {
//            [_pictureArray addObject:photos[i]];
//        }
//    }
    [_pictureArray addObject:photos[0]];
    [self reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

@end
